--[[
Copyright (C) 2018-2021 The AGYS Windmill Open Source Project

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
]]

--require"import"
local bind=luajava.bindClass
local PendingIntent=bind"android.app.PendingIntent"
local LuaAppliaction=bind"com.androlua.LuaApplication".getInstance()
local RemoteViews=bind"android.widget.RemoteViews"
local Intent=bind"android.content.Intent"
--local DetailActivity=bind"com.windmill.widget.OneWordDetailActivity"
local LuaActivity=bind"com.androlua.LuaActivity"
--local Toast=bind"android.widget.Toast"
local Http=bind"com.androlua.Http"
--local android_sdk=bind"android.os.Build$VERSION".SDK_INT
--local Log=bind"android.util.Log"
--print(pcall(function() require"cjson" require"json" end))
local json=require"cjson"
--local insert=table.insert
local Uri=bind"android.net.Uri"

local onewordConfig
local function getPref(context)
if onewordConfig==nil then
onewordConfig=require"widget_config/oneword"
:new(context)
end
return onewordConfig
end

local function getClickIntent(act,hitokoto,id,context)
if act=="" then
return nil
elseif act=="windmill" then
--返回程序
return PendingIntent.getActivity(
context,id,
context.getPackageManager()
.getLaunchIntentForPackage(
context.getPackageName()
),
67108864
)
elseif act=="detail" then
--详情页
return PendingIntent.getActivity(
context,id,
Intent()
.setClass(context--[[.getApplicationContext()]],
LuaActivity--DetailActivity
)
--.putExtra("formDetail",true)
--.putExtra("hitokoto",hitokoto)
--.putExtra("appWidgetId",int(id))
.setData(Uri.parse(LuaAppliaction.getLuaDir().."/soup.lua"))
.putExtra("arg",luajava.bindClass"java.lang.Object"{json.decode(hitokoto).hitokoto}),
67108864|134217728
)
end
--刷新
return PendingIntent.getBroadcast(
context,id,
Intent()
.setAction("android.appwidget.action.APPWIDGET_UPDATE")
.setClass(context--[[.getApplicationContext()]],
this.getClass()
)
.putExtra("appWidgetIds",int{id}),
67108864|134217728
)
end

local function setTextViewHitokoto(context,widget_config,n,id,view)
local info=json.decode(n)
--print("setTextViewHitokoto",n)
view.setTextViewText(0x7f060000,
info.hitokoto
)
.setTextViewText(0x7f060001,
info.from
)
.setInt(0x7f060001,"setVisibility",0)
.setOnClickPendingIntent(16908288,
getClickIntent(
widget_config:getClickAction(id)
,n,id,context
)
)
end

------------------------

function onReceive(context,intent)
--print("receive",this,context,intent,intent.getAction())
--[[if intent.getAction()=="com.windmill.widget.action.UPDATE" then
print("do refresh: com.windmill.widget.action.UPDATE")
--从详情页刷新，重发广播
context.sendBroadcast(Intent()
.setAction("android.appwidget.action.APPWIDGET_UPDATE")
.setClass(context.getApplicationContext(),
this.getClass()
)
.putExtra("appWidgetIds",int{
intent.getIntExtra("appWidgetId",0)
})
)
end]]
end

function onEnabled(context)
--print("enabled",this,context)
if LuaAppliaction.getSharedData("widget_resize_tiped") then
return
end
bind"android.widget.Toast"
.makeText(context,
"长按微件可调整大小",
0)
.show()
LuaAppliaction.setSharedData("widget_resize_tiped",true)
end

function onDisabled(context)
--print("disabled",this,context)
getPref(context):clearAllConfig()
end

function onDeleted(context,ids)
--print("deleted",this,context,id)
--print(ids,type(ids),type(ids[0]))
--[[context.sendBroadcast(Intent()
.setAction("windmill.widget.oneword.REMOVED")
.putExtra("appWidgetIds",ids)
)]]
local widget_config=getPref(context)
local stored_ids=widget_config:getIds()
local data=widget_config:getAllConfig()
.keySet().toArray()
for k=0,#ids-1 do
local sid=tostring(ids[k])
local pos=table.find(stored_ids,sid)
if pos then
--print("removed",sid)
table.remove(stored_ids,pos)
end
local find=("^%s_"):format(sid)
for k=0,#data-1 do
local v=data[k]
if v:find(find) then
widget_config:removeConfig(v)
end
end
end
widget_config:putIds(stored_ids)
end

function onUpdate(context,widget,ids)
--print("update",this,context,widget,ids,#ids)
--print(ids,type(ids),type(ids[0]))
local widget_config=getPref(context)
local pack_name=context.getPackageName()
local stored_ids=widget_config:getIds()
local added={}
--print("ids",dump(stored_ids),
--dump(luajava.astable(ids))
--)
--print(ids,ids[0],ids[1],"ids 1-2")
--print("stored",stored_ids[1],type(stored_ids[1]))
--[[for k,v in ipairs(stored_ids) do
print("foreach stored",v,type(v))
end]]
local isVip=LuaAppliaction.getSharedData("vip_time")~=nil
 and LuaAppliaction.getSharedData("vip_time")~="已到期"
 and LuaAppliaction.getSharedData("vip_time")~="未开通"
for k=0,#ids-1
--_,id in ipairs(luajava.astable(ids))
do
local id=ids[k]
--print("foreach id",id,type(id))
local sid=tostring(id)
--print("find",sid,type(sid),"found",table.find(stored_ids,sid))
if table.find(stored_ids,sid)==nil then
--print("new id"..id..", "..sid)
--print("newId",type(id),type(sid))
table.insert(stored_ids,sid)
table.insert(added,sid)
--widget_config:setIsNew(sid,true)
end
local textSize=widget_config:getTextSize(id)
local view=RemoteViews(pack_name,
widget_config.getLayoutRes(widget_config:getStyle(id))
)
.setTextViewTextSize(0x7f060000,1,textSize)
.setTextViewTextSize(0x7f060001,1,textSize-2)
if isVip then
--刷新
view.setOnClickPendingIntent(16908288,
PendingIntent.getBroadcast(
context,id,
Intent()
.setAction("android.appwidget.action.APPWIDGET_UPDATE")
.setClass(context--[[.getApplicationContext()]],
this.getClass()
)
.putExtra("appWidgetIds",int{id}),
67108864|134217728
)
)
--id=int(id)
--从详情页刷新
local toSet=widget_config:getPendingSentence(id)
--print("pending sentence: ",toSet,toSet!="")
if toSet!="" then
setTextViewHitokoto(context,widget_config,toSet,id,view)
widget_config:setPendingSentence(id,"")
widget.updateAppWidget(id,view)
continue
end
--正常刷新逻辑
view.setTextViewText(
0x7f060000,
"正在获取句子"
)
.setTextViewText(0x7f060001,"")
.setInt(0x7f060001,"setVisibility",8)
--[[主页
.setOnClickPendingIntent(16908288,
PendingIntent.getActivity(
context,id,
context.getPackageManager()
.getLaunchIntentForPackage(pack_name),
67108864
)
)]]
--初始更新
widget.updateAppWidget(id,view)
--.partiallyUpdateAppWidget(id,view)
Http.get("https://v1.hitokoto.cn/?encode=json",function(c,n)
if c!=200 then
--获取缓存的句子
n=widget_config:getSentence(id)
if n=="" then
n=nil
end
else
widget_config:setSentence(id,n)
--print("text update",id,n)
--[[context.sendBroadcast(Intent()
.setAction("windmill.widget.oneword.TEXT_UPDATED")
.putExtra("hitokoto",n)
.putExtra("appWidgetIds",int{id})
.putExtra("appWidgetId",int(id))
)]]
local h=widget_config:getHistory()
table.insert(h,1,n)
widget_config:putHistory(h)
end
--print(c,n)
if n then
setTextViewHitokoto(context,widget_config,n,id,view)
else
view.setTextViewText(
0x7f060000,
"无法获取句子，点按重试"
)
--.setTextViewText(0x7f060001,"")
end
widget.updateAppWidget(id,view)
end)
else
view.setTextViewText(
0x7f060000,
"成为会员即可查看"
)
.setTextViewText(0x7f060001,"")
.setInt(0x7f060001,"setVisibility",8)
--主页
.setOnClickPendingIntent(16908288,
PendingIntent.getActivity(
context,id,
context.getPackageManager()
.getLaunchIntentForPackage(pack_name),
67108864
)
)
--初始更新
widget.updateAppWidget(id,view)
end
end
if #added>0 then
--[[context.sendBroadcast(Intent()
.setAction("windmill.widget.oneword.ADDED")
.putExtra("appWidgetIds",int(added))
)]]
--print("finalPut",type(stored_ids[1]))
widget_config:putNewIds(added)
widget_config:putIds(stored_ids)
end
stored_ids--[[,added]]=nil
end
